<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/Home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容卡片区 -->
    <el-card class="box-card">
      <!-- 头部警告条 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
        show-icon
      >
      </el-alert>
      <!-- 分类参数级联选择框 -->
      <div class="block">
        <span class="demonstration">选择商品分类:</span>
        <el-cascader
          clearable
          v-model="value"
          :options="sortlist"
          :props="options"
          @change="handleChange"
          @visible-change="visiblechange"
        ></el-cascader>
      </div>
      <!-- 分类页签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="value.length !== 3"
            @click="postmany"
            >添加参数</el-button
          >
          <!-- 动态表格 -->
          <el-table :data="datasort" style="width: 100%">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(tag, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="#" type="index"> </el-table-column>
            <!-- 参数列 -->
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
                <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                :disabled="value.length !== 3"
                size="mini"
                @click="editparameter(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                :disabled="value.length !== 3"
                size="mini"
                 @click="deleteparameter(scope.row)"
                >删除</el-button
              >
                </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="value.length !== 3"
            @click="postonly"
            >添加属性</el-button
          >
          <!-- 添加静态表格 -->
          <el-table :data="datasort" style="width: 100%">
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  :key="index"
                  v-for="(tag, index) in scope.row.attr_vals"
                  closable
                  :disable-transitions="false"
                  @close="handleClose(tag, scope.row)"
                >
                  {{ tag }}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column label="#" type="index"> </el-table-column>
            <!-- 参数列 -->
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <!-- 操作列 -->
            <el-table-column label="操作">
                <template slot-scope="scope">
              <el-button
                type="primary"
                icon="el-icon-edit"
                :disabled="value.length !== 3"
                size="mini"
                @click="editparameter(scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                icon="el-icon-delete"
                :disabled="value.length !== 3"
                size="mini"
                @click="deleteparameter(scope.row)"
                >删除</el-button
              >
                </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加动态或静态数据对话框 -->
      <el-dialog title="添加参数" :visible.sync="dialogFormVisible" @close='close'>
          <!-- 大坑 ref 记得加冒号 是变量 不是字符串 -->
        <el-form :model="form" :rules="rules" :ref="form">
          <el-form-item label="参数名称:" label-width="120px" prop="attr_name">
            <el-input v-model="form.attr_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <!-- 大坑 click="dialogForm(form) 记得传参数-->
          <el-button type="primary" @click="dialogForm(form)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
       <!-- 编辑动态或静态数据对话框 -->
      <el-dialog title="编辑参数" :visible.sync="dialogFormVisible1" @close='close'>
          <!-- 大坑 ref 记得加冒号 是变量 不是字符串 -->
        <el-form :model="form" :rules="rules" :ref="form">
          <el-form-item label="参数名称:" label-width="120px" prop="attr_name">
            <el-input v-model="form.attr_name" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <!-- 大坑 click="dialogForm(form) 记得传参数-->
          <el-button type="primary" @click="setparameter(form)"
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
        dialogFormVisible1:false,//编辑动态或静态数据对话框开关
        dialogFormVisible:false,//添加动态或静态数据对话框开关
        // 添加动态或静态数据
        form:{
            attr_name:''
        },
        //  form数据校验规则
         rules: {
          attr_name: [
            { required: true, message: '请输入参数名称', trigger: 'blur' },
          ],},
      inputVisible: false,
      inputValue: "", //tag标签输入框值
      //分类参数级联选择框的值
      value: [],
      //   分类列表
      sortlist: [],
      //   分类ID
      sortID: 0,
     //   参数ID
      attr_id:0,
      //   页签名
      activeName: "many",
      datasort: [], //动态 或静态 分类数据
      // 级联选择器数据规则
      options: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
    };
  },
  methods: {
    // 分类参数级联选择框的值发生改变触发函数
    handleChange(val) {
      this.value = val;
      if (this.value.length !== 3) {
        this.value = [];
        return;
      }
      this.sortID = this.value[this.value.length - 1];
      this.getdatasort();
    },
    // 获取分类列表
    async visiblechange(val) {
      if (val) {
        const { data: res } = await this.$http.get("categories");
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.sortlist = res.data;
        console.log(this.sortlist);
      }
    },
    //  页签切换触发函数 handleClick()
    handleClick() {
      console.log(this.activeName, this.sortID);
      this.getdatasort();
    },
    // 获取 静态 或动态 属性 数据
    async getdatasort() {
      // 动态属性
      if (this.activeName === "many" && this.value.length === 3) {
        let { data: res } = await this.$http.get(
          `categories/${this.sortID}/attributes`,
          { params: { sel: this.activeName } }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals?item.attr_vals.split(" ") : [];
           item.inputVisible=false
           item.inputValue=''
        });
        this.datasort = res.data;
        console.log(res);
      }
      // 静态属性
      if (this.activeName === "only" && this.value.length === 3) {
        let { data: res } = await this.$http.get(
          `categories/${this.sortID}/attributes`,
          { params: { sel: this.activeName } }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        // 递归函数得到 attr_vals 的字符串
        res.data.forEach((item) => {
          //  再将 attr_vals 进行分割得到数组
          item.attr_vals =item.attr_vals?item.attr_vals.split(" ") : [];
          item.inputVisible=false
          item.inputValue=''
        });

        this.datasort = res.data;
        console.log(res);
      }
    },
    // tag标签关闭时触发函数
   async handleClose(tag, scope) {
      scope.attr_vals.splice(scope.attr_vals.indexOf(tag), 1);
      const {data:res}=await this.$http.put(`categories/${this.sortID}/attributes/${scope.attr_id}`,{attr_name:scope.attr_name,attr_sel:scope.attr_sel,attr_vals:scope.attr_vals.toString()})
      if(res.meta.status===200){
        return this.$message({
          message: res.meta.msg,
          type: 'success ' });
      }
      // console.log(res);
    },
    // 展示taginput输入框的值同时获取焦点,注意这里的input是对象
    showInput(input) {
     input.inputVisible= true;
      // console.log(inputVisible);
      this.$nextTick(() => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // taginput输入框失去焦点时触发函数
   async handleInputConfirm(scope) {
      let inputValue1 = scope.inputValue;
      if (inputValue1) {
       scope.attr_vals.push(inputValue1);
      //  数组转为字符串用方法join(' ')记得用空格分开
       const {data:res}=await this.$http.put(`categories/${this.sortID}/attributes/${scope.attr_id}`,{attr_name:scope.attr_name,attr_sel:scope.attr_sel,attr_vals:scope.attr_vals.join(" ")})
        if(res.meta.status===200){
          scope.inputVisible = false;
          scope.inputValue = "";
          //  console.log(res);
          return this.$message({
          message: res.meta.msg,
          type: 'success ' });
      }
      
      }
     
    },
    //打开添加静态属性
    postonly() {
        this.dialogFormVisible=!this.dialogFormVisible
    },
    //打开添加动态参数
    postmany() {
        this.dialogFormVisible=!this.dialogFormVisible
    },
    // 提交动态参数 或 静态属性输入框数据
   async dialogForm(formName){
       this.$refs[formName].validate(async(valid) => {
          if (valid) {
          const {data:res}=await  this.$http.post(`categories/${this.sortID}/attributes`,{attr_sel:this.activeName,attr_name:this.form.attr_name})
        //   console.log(res);
          this.dialogFormVisible=!this.dialogFormVisible
          this.getdatasort()
          return this.$message({
          message: res.meta.msg,
          type: 'success ' });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
    },
    // 表单校验实例
    resetForm(formName) {
        this.$refs[formName].resetFields();
      },
    //   动态参数 或 静态属性输入框关闭 回调函数
      close(){
          this.form.attr_name=''
      },
    //   删除参数
     deleteparameter(parameter){
        //  console.log(2222);
        this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
           const {data:res}=await  this.$http.delete(`categories/${this.sortID}/attributes/${parameter.attr_id}`)
        if(res.meta.status===200){
             this.getdatasort()
         return this.$message({
          message: res.meta.msg,
          type: 'success ' });
        }
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
       
      },
    //  打开 编辑参数框 回调函数
     async editparameter(parameter){
        this.dialogFormVisible1=!this.dialogFormVisible1
        this.attr_id=parameter.attr_id
      },
      //编辑提交
      setparameter(formName){
          this.$refs[formName].validate(async(valid) => {
          if (valid) {
          const {data:res}=await this.$http.put(`categories/${this.sortID}/attributes/${this.attr_id}`,{attr_sel:this.activeName,attr_name:this.form.attr_name})
          this.dialogFormVisible1=!this.dialogFormVisible1
          this.getdatasort()
          return this.$message({
          message: res.meta.msg,
          type: 'success ' });
          } else {
            console.log('error submit!!');
            return false;
          }
        });
   
      }
  },
};
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>